package com.asiainfo.framework.boot;

import com.asiainfo.framework.annotation.ExcludeAutoConfiguration;
import com.asiainfo.framework.utils.ClassScaner;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.TypeFilter;

import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

import static com.asiainfo.common.constants.Constants.PROJECT_BASE_PACKAGE;

/**
 * 自定义排除 @ExcludeAutoConfiguration 过滤器
 */
public class CustomConfigurationExcludeFilter implements TypeFilter {


    public static Set<String> EXCLUDE_NAMES;

    static {
        initExcludeNameByAnnotation();
    }

    private static void initExcludeNameByAnnotation() {
        Set<Class<?>> classes = new HashSet<>();
        ClassScaner.scan(PROJECT_BASE_PACKAGE, ExcludeAutoConfiguration.class)
                .stream()
                .forEach(c -> {
                    ExcludeAutoConfiguration annotation =
                            AnnotatedElementUtils.findMergedAnnotation(c, ExcludeAutoConfiguration.class);
                    Class<?>[] value = annotation.value();
                    Collections.addAll(classes, value);
                });
        Set<String> names = classes.stream().map(c -> c.getName()).collect(Collectors.toSet());
        Collections.unmodifiableSet(names);
        EXCLUDE_NAMES = names;
    }

    public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
        String className = metadataReader.getAnnotationMetadata().getClassName();
        return EXCLUDE_NAMES.contains(className);
    }
}
